<?php

class AttachHelper extends Helper {

    var $AttachModel;
    var $AttachUpload;
    var $FtpUpload;
    var $UploadRow = array();

    public function __construct($member, $table) {
        $this->AttachModel = $this->LoadModel('Public');
        $this->UploadRow = array(
            'id' => NOW_TIME . StringCode::RandomCode(8, 'num'),
            'class' => $table,
            'member' => $member,
            'dateline' => NOW_TIME,
            'ftp' => '0',
            'ftpurl' => '/attach'
        );
        $this->AttachUpload = new AttachUpload();
    }

    /**
     * base64上传
     * 2018-3-14
     * @param type $base64
     * @return boolean
     */
    public function base64Upload($base64) {
        $base64_image = str_replace(' ', '+', $base64);
        //$base64_image = $base64;
        //post的数据里面，加号会被替换为空格，需要重新替换回来，如果不是post的数据，则注释掉这一行
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image, $result)){
            //匹配成功
//            if($result[2] == 'jpeg'){
//                $image_name = uniqid().'.jpg';
//                //纯粹是看jpeg不爽才替换的
//            }else{
//                $image_name = uniqid().'.'.$result[2];
//            }
            $type = $result[2];
            if(in_array($type, array('pjpeg','jpeg','jpg','gif','bmp','png'))){
                $image_name = NOW_TIME . StringCode::RandomCode(8, 'num').'.jpg';
                $up_config = Config::GetUpload();
                $save_path = WEB_PATH . '/'.$up_config['savepath']. '/' . date('Ym') . '/' . date('d');
                $this->AttachUpload->MakeDir($save_path);
                $image_file = $save_path . "/". $image_name;
                $file_path = '/' . $up_config['savepath']. '/' . date('Ym') . '/' . date('d'). '/' . $image_name;
                //服务器文件存储路径
                if (file_put_contents($image_file, base64_decode(str_replace($result[1], '', $base64_image)))){
                    //缩略图
                    $this->LoadResurces('image/class.image');
                    $image = new Image($save_path);
                    $thumb_image = $image->thumb($image_name, 200, 200, 's_');
                    //FTP上传
                    $this->LoadHelper('FtpUploadHelper');
                    $FtpUploadHelper = new FtpUploadHelper();
                    $FtpUploadHelper->Set(0, 'image');
                    $up_ftp = 0;
                    if (false != ($UploadRow = $FtpUploadHelper->Submit(array('url' => $file_path, 'name' => $image_name)))) {
//                        $this->UploadRow['ai_path'] = $FileFilter['url'];
//                        $this->UploadRow['ai_ftp'] = $UploadRow['ftp'];
//                        $this->UploadRow['ai_ftpurl'] = $UploadRow['ftpurl'];
                        $up_ftp = 1;
                    }
                    return array('errcode' => 0, 'msg' => '上传成功', 'data' => array(
                        'name' => '',
                        'url' => str_replace(WEB_PATH, '', $save_path . '/' . $image_name),
                        'size' => '',
                        'type' => $type,
                        'save_path' => $file_path,
                        'up_ftp' => $up_ftp,
                        'ai_path' => str_replace(WEB_PATH, '', $save_path . '/' . $image_name),
                        'thumb_path' => BASE_ATTACH . str_replace(WEB_PATH, '', $save_path . '/' . $image_name)
                    ));
                }else{
                    return array('errcode' => 1002, 'msg' => '上传失败', 'data' => array());
                } 
            }else{
                return array('errcode' => 1001, 'msg' => '文件格式不符', 'data' => array());
            }

        }else{
            return array('errcode' => 1000, 'msg' => '未知错误,可能是禁止的图片格式或非图片文件导致!', 'data' => array());
        }
    }

    /** 上传图片处理
     *
     * @param unknown $LoginFailed
     * @param unknown $param
     * @return multitype:number string unknown Ambigous <> */
    public function upImage($file) {
        $FileFilter = $this->AttachUpload->UploadFile($file);
        if(isset($FileFilter['success']) && $FileFilter['success'] == false) return $FileFilter;
        $this->UploadRow['title'] = $file['name'];
        $this->UploadRow['path'] = $FileFilter['url'];
        $this->UploadRow['size'] = $FileFilter['size'];
        if (function_exists('exif_read_data')) {
            $exif = exif_read_data($file['tmp_name']);
            $this->UploadRow['filetime'] = empty($exif['FileDateTime']) ? NOW_TIME : $exif['FileDateTime'];
        }

        $this->LoadResurces('image/class.image');
        $image = new Image($FileFilter['save_path']);
        $thumb_image = $image->thumb($FileFilter['name'], 200, 200, 's_');
        
        $this->LoadHelper('FtpUploadHelper');
        $FtpUploadHelper = new FtpUploadHelper();
        $FtpUploadHelper->Set(0, 'image');
        if (false != ($UploadRow = $FtpUploadHelper->Submit($FileFilter))) {
            //$this->UploadRow['ai_path'] = $UploadRow['path'];
            $this->UploadRow['ai_path'] = $FileFilter['url'];
            $this->UploadRow['ai_ftp'] = $UploadRow['ftp'];
            $this->UploadRow['ai_ftpurl'] = $UploadRow['ftpurl'];
        }
        
        $this->UploadRow['ai_title'] = $this->UploadRow['title'];
        $this->UploadRow['ai_size'] = $this->UploadRow['size'];
        $this->UploadRow['ai_class'] = $this->UploadRow['class'];
        $this->UploadRow['ai_dateline'] = $this->UploadRow['dateline'];
        $this->UploadRow['ai_member'] = $this->UploadRow['member'];
        $this->UploadRow['ai_no'] = $FileFilter['name'];
        $this->UploadRow['ai_ftpurl'] = BASE_ATTACH; //临时使用
        $this->UploadRow['ai_path'] = $FileFilter['url']; //临时使用
        $this->UploadRow['thumb_path'] = BASE_ATTACH . str_replace($FileFilter['name'], $thumb_image, $FileFilter['url']);
        $this->AttachModel->save('attach_image', $this->UploadRow);
        return $this->UploadRow;
    }

    public function imageUpdate($no, $table) {
        $this->AttachModel->update('attach_image', array('ai_class' => $table, 'ai_no' => $no), array('`ai_id` = ?' => $this->UploadRow['id']));
    }

    public function imageRemove($where) {
        $ImageAll = $this->AttachModel->getList('attach_image', '*', $where, null, null, null, false);
        foreach ($ImageAll AS $value) {
            if (empty($value['ai_ftp'])) {
                @unlink(WEB_PATH . $value['ai_path']);
            } else {
                $FtpUploadHelper = new FtpUploadHelper();
                $FtpUploadHelper->Set($value['ai_ftp']);
                $FtpUploadHelper->FtpUpload->FtpChdir($FtpUploadHelper->FtpUpload->_Config['dir'] . dirname($value['ai_path']));
                $FtpUploadHelper->FtpUpload->FtpDelete(basename($value['ai_path']));
                $FtpUploadHelper->FtpUpload->FtpClose();
            }
            $this->AttachModel->delete('attach_image', $where);
        }
    }

    /** 上传文件处理
     *
     * @param unknown $LoginFailed
     * @param unknown $param
     * @return multitype:number string unknown Ambigous <> */
    public function upFile($file) {
        $FileFilter = $this->AttachUpload->UploadFile($file);
        $this->UploadRow['title'] = $file['name'];
        $this->UploadRow['path'] = $FileFilter['url'];
        $this->UploadRow['size'] = $FileFilter['size'];
        $this->UploadRow['af_path'] = $FileFilter['url'];
        
        $this->LoadHelper('FtpUploadHelper');
        $FtpUploadHelper = new FtpUploadHelper();
        $FtpUploadHelper->Set(0, 'file');
        if (false != ($UploadRow = $FtpUploadHelper->Submit($FileFilter))) {
            //$this->UploadRow['af_path'] = $UploadRow['ftpurl'] . $UploadRow['path'];
            $this->UploadRow['af_path'] = $FileFilter['url'];
            $this->UploadRow['af_ftp'] = $UploadRow['ftp'];
            $this->UploadRow['af_ftpurl'] = $UploadRow['ftpurl'];
        }
        $this->UploadRow['af_title'] = $this->UploadRow['title'];
        // $this->UploadRow['af_title'] = $file['name'];
        $this->UploadRow['af_size'] = $this->UploadRow['size'];
        $this->UploadRow['af_class'] = $this->UploadRow['class'];
        $this->UploadRow['af_dateline'] = $this->UploadRow['dateline'];
        $this->UploadRow['af_uid'] = $this->UploadRow['member'];
        $this->UploadRow['af_no'] = $FileFilter['name'];
        $this->UploadRow['af_ftpurl'] = BASE_ATTACH; //临时使用
        $this->UploadRow['af_path'] = $FileFilter['url']; //临时使用
        $this->AttachModel->save('attach_file', $this->UploadRow);
        return $this->UploadRow;
    }

    public function fileUpdate($no, $table) {
        $this->AttachModel->update('attach_file', array('af_class' => $table, 'af_no' => $no), array('`af_id` = ?' => $this->UploadRow['id']));
    }

    public function fileRemove($where) {
        $ImageAll = $this->AttachModel->getList('attach_file', '*', $where, null, null, null, false);
        foreach ($ImageAll AS $value) {
            if (empty($value['af_ftp'])) {
                @unlink(WEB_PATH . $value['af_path']);
            } else {
                $FtpUploadHelper = new FtpUploadHelper();
                $FtpUploadHelper->Set($value['af_ftp']);
                $FtpUploadHelper->FtpUpload->FtpChdir($FtpUploadHelper->FtpUpload->_Config['dir'] . dirname($value['af_path']));
                $FtpUploadHelper->FtpUpload->FtpDelete(basename($value['af_path']));
                $FtpUploadHelper->FtpUpload->FtpClose();
            }
            $this->AttachModel->delete('attach_file', $where);
        }
    }
    
    public function imageRow($where){
        if(is_numeric($where)){
            $where = array(
                '`ai_id` = ?' => $where
            );
        }
        $model = $this->LoadModel('Public');
        return $model->getOneRow('attach_image', '*', $where);
    }

    public function imageRow2($attach_arr,$url){
        $count = count($attach_arr);
        for($i=0;$i<$count;$i++){
            if($attach_arr[$i]['url'] == $url){
                $attach = $attach_arr[$i];
                break;
            }
        }
        return $attach;
    }

    public function imageList($oid){
        $model = $this->LoadModel('Public');
        $attach_arr = $model->getList('attachment','*', array('`ot_oid` =?' =>$oid));
        return $attach_arr;
    }
    
    public function fileRow($where){
        if(is_numeric($where)){
            $where = array(
                '`af_id` = ?' => $where
            );
        }
        $model = $this->LoadModel('Public');
        return $model->getOneRow('attach_file', '*', $where);
    }

    public function attachSave($data = array()){
        $model = $this->LoadModel('Public');
        $data['created_at'] = time();
        $at_id = $model->save('attachment', $data);
        return $at_id;
    }
}